package com.example.testdb1.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.testdb1.entity.result.R;
import com.example.testdb1.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(urlPatterns = "/*")// /*表示拦截所有请求
@Slf4j
public class DemoFilter implements Filter {

    //初始化方法，只调用一次
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("filter初始化方法被调用");
        Filter.super.init(filterConfig);
    }

    //拦截到请求之后调用，调用多次
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的url
        String requestURL = request.getRequestURL().toString();
        log.info("requestURL:{}", requestURL);
        //1.如果是登录请求，放行  如果是swagger，也放行
        if (requestURL.contains("/login") || request.getRequestURI().contains("/doc.html")|| request.getRequestURI().startsWith("/swagger-")
                || request.getRequestURI().startsWith("/v2/api-docs") || request.getRequestURI().startsWith("/webjars")) {
            filterChain.doFilter(request, response);
            //结束当前方法
            return;
        }

        //2.检验jwt是否存在，并且是否有效
        String token = request.getHeader("token");
        //判断token是否存在
        if (!StringUtils.hasLength(token)) {
            //jwt不存在，直接返会错误状态码
            log.error("token不存在");
            R<Object> responseResult = R.error("NOT_LOGIN");

            String jsonString = JSONObject.toJSONString(responseResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);
            return;
        }
        //3.校验token是否有效,无效直接返回错误信息
        try {
            JwtUtils.resolveJwt(token);
        } catch (Exception e) {
            R<Object> responseResult = R.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(responseResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);
            return;
        }
        //4.放行
        filterChain.doFilter(request, response);
    }

    //销毁方法，调用一次
    @Override
    public void destroy() {
        System.out.println("执行了销毁方法");
        Filter.super.destroy();
    }
}
